﻿namespace CN2P.Web.Controllers.Api
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    using CN2P.ServiceModel;
    using CN2P.Web.Db;

    public class OrdersApiController : BaseApiController
    {
        [AcceptVerbs("GET")]
        public IList<OrderModel> Get(string userId)
        {
            var decodedUserId = this.DecodeUserId(userId);
            using (var context = new ECommerceDataContext())
            {
                return context.Orders
                              .Where(item => item.UserId == decodedUserId)
                              .Select(item => Map(item))
                              .ToList();
            }
        }

        [AcceptVerbs("GET")]
        public OrderModel GetOrder(string userId, string orderId)
        {
            var decodedUserId = this.DecodeUserId(userId);
            using (var context = new ECommerceDataContext())
            {
                var order = context.Orders
                                   .FirstOrDefault(item => item.UserId == decodedUserId && item.Id == orderId);
                if (order == null)
                {
                    throw new HttpResponseException(this.NotFound("order-not-found", "Order is not found"));
                }

                return Map(order);
            }
        }

        [AcceptVerbs("DELETE")]
        public HttpResponseMessage DeleteAll()
        {
            using (var context = new ECommerceDataContext())
            {
                context.ExecuteCommand("DELETE FROM [OrderItem]");
                context.ExecuteCommand("DELETE FROM [Order]");
            }

            return Request.CreateResponse(HttpStatusCode.Created);
        }

        private OrderModel Map(Order order)
        {
            return new OrderModel
            {
                OrderId = order.Id,
                UserId = order.UserId,
                OrderDate = order.OrderDate.ToString("yyyy-MM-dd hh:mm:ss"),
                TotalValue = order.TotalValue,
                Items = order.OrderItems.Select(Map).ToList()
            };
        }

        private OrderItemModel Map(OrderItem orderItem)
        {
            return new OrderItemModel
                {
                    ProdId = orderItem.ProdId,
                    ProdName = orderItem.ProdName,
                    ProdDesc = orderItem.ProdDesc,
                    ProdPrice = orderItem.ProdPrice,
                    ImageUrl = orderItem.ImageUrl,
                    Quantity = orderItem.Quantity
                };
        }
    }
}
